function M = extraPluvio(filena,delimiter,date1,date2)
%
%extraPluvio - Pluviometric data extraction
%
%M = extraPluvio(FILENA,Delimiter,date1,date2)
%
% Input data:
%
%   FILENA     : name of the input ASCII or xls/xlsx Excel file. If FILENA 
%                is undefined or empty, the filename is interactively 
%                managed. The columns of the input data are
%                       [date value]
%                where date is in one of the following forms:
%                   yyyy-mm-dd HH:MM:SS 
%                   yyyy-mm-dd HH:MM
%                   yyyy-mm-dd
%                   dd/mm/yyyy HH:MM
%                   dd/mm/yyyy
%                and value are numerical data
%
%   Delimiter  : Delimiter of the input ASCII file (of course, such a 
%                variable is active only if the input file is ASCII). If 
%                undefined or empy, Delimiter = ',' is used. 
%
%   Limit dates: [date1 date2]. If date1 (date2) is undefined or empty, 
%                no lower (higher) limit date is considered. The limit
%                dates must be expressed in numeric serial form.
%
% Output data:
%
%   M = [t P], where t is the time (in MATLAB serial number form) and P
%   is the corresponding pluviometric data.  
%
% See also cumPluvio.

if (nargin < 1) || isempty(filena)
    [filename, pathname] = uigetfile(...
        {'*.xlsx';'*.xls';'*.txt'},'INPUT FILE');
    filena = fullfile(pathname,filename);
end
if (nargin < 2) || isempty(delimiter)
    delimiter = ',';
end
if nargin < 3
    date1 = [];
end
if nargin < 4
    date2 = [];
end

[~,~,ext] = fileparts(filena);
if strcmpi(ext,'.xls') || strcmpi(ext,'.xlsx')
    [a,b] = xlsread(filena);
else
    FID = fopen(filena);
    C = textscan(FID,'%s%f','delimiter',delimiter);
    fclose(FID);
    a = C{2};
    b = C{1};
end
nv = length(b);
M = zeros(nv,2);
M(:,2) = a;

for k = 1:nv
    bk = b{k};
    dk = obsdate(bk);
    M(k,1) = dk;
end

if ~isempty(date1)
    I1 = M(:,1) < date1;
    if sum(I1) > 0
        M(I1,:) = [];
    end
end
if ~isempty(date2)
    I2 = M(:,1) > date2;
    if sum(I2) > 0
        M(I2,:) = [];
    end
end

function dk = obsdate(bk)
bk = char(bk);
if strcmpi(bk(3),'/') 
    dd = str2double(bk(1:2));
    mm = str2double(bk(4:5));
    yy = str2double(bk(7:10));
else
    yy = str2double(bk(1:4));
    mm = str2double(bk(6:7));
    dd = str2double(bk(9:10));
end
h = 0;
m = 0;
s = 0;
if length(bk) > 10
    h  = str2double(bk(12:13));
    if length(bk) > 13
        m  = str2double(bk(15:16));
        s  = str2double(bk(18:19));
    end
end
dk = datenum(yy,mm,dd,h,m,s);